package cn.s1995.sloth.bizs.util;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.experimental.UtilityClass;

import java.util.List;
import java.util.Objects;

/**
 * PageUtil
 *
 * @author Lex
 * @description 分页工具类
 * @date 2024/05/23 10:07
 */
@UtilityClass
public class PageUtil {
    /**
     * 字段-createTime
     */
    public static final String FIELD_CREATE_TIME = "create_time";

    /**
     * 字段-id
     */
    public static final String FIELD_ID = "id";

    /**
     * 字段-id
     */
    public static final String DOT = ".";

    /**
     * 设置默认排序
     *
     * @param page       分页对象
     * @param tableAlias 表别名
     */
    public static void setDefaultOrders(Page page, String... tableAlias) {
        if (Objects.isNull(page)) {
            return;
        }

        String dot = DOT;
        String[] columns = new String[2];
        if (tableAlias != null && tableAlias.length > 0) {
            if (tableAlias.length == columns.length) {
                for (int i = 0; i < columns.length; i++) {
                    columns[i] = tableAlias[i] + dot + FIELD_CREATE_TIME;
                }
            } else {
                columns[0] = tableAlias[0] + dot + FIELD_CREATE_TIME;
                columns[1] = tableAlias[0] + dot + FIELD_ID;
            }
        } else {
            columns[0] = FIELD_CREATE_TIME;
            columns[1] = FIELD_ID;
        }
        // 添加默认排序条件
        if (Objects.nonNull(page.getOrders()) && page.getOrders().size() > 0) {
            List<OrderItem> orderItems = OrderItem.descs(columns);
            // 将自定义排序条件放在默认排序条件之后
            orderItems.addAll(page.getOrders());
            page.setOrders(orderItems);
        } else {
            // 使用默认排序条件
            page.setOrders(OrderItem.descs(columns));
        }
    }
}
